import { create } from 'zustand';
import { EditorState, UserSettings, ValidationResult, PreviewMode, DEFAULT_SETTINGS, EXAMPLE_YAML } from '../types';
import { validateYAML } from '../utils/yaml';
import { saveContent, loadContent, saveSettings, loadSettings } from '../utils/storage';

interface EditorStore {
  // 编辑器状态
  content: string;
  cursorPosition: number;
  isDirty: boolean;
  filename: string;
  lastModified: Date;
  
  // 用户设置
  settings: UserSettings;
  
  // 验证结果
  validation: ValidationResult;
  
  // 预览模式
  previewMode: PreviewMode;
  
  // 应用状态
  isLoading: boolean;
  error: string | null;
  
  // 编辑器操作
  setContent: (content: string) => void;
  setCursorPosition: (position: number) => void;
  setFilename: (filename: string) => void;
  markDirty: () => void;
  markClean: () => void;
  
  // 设置操作
  updateSettings: (settings: Partial<UserSettings>) => void;
  resetSettings: () => void;
  
  // 验证操作
  validateContent: () => void;
  
  // 预览操作
  setPreviewMode: (mode: PreviewMode) => void;
  
  // 应用状态操作
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  
  // 文件操作
  newFile: () => void;
  loadFile: (content: string, filename?: string) => void;
  saveFile: () => void;
  
  // 初始化
  initialize: () => void;
}

export const useEditorStore = create<EditorStore>((set, get) => ({
  // 初始状态
  content: '',
  cursorPosition: 0,
  isDirty: false,
  filename: 'untitled.yaml',
  lastModified: new Date(),
  
  settings: DEFAULT_SETTINGS,
  
  validation: {
    isValid: true,
    errors: [],
    warnings: [],
    lastValidated: new Date()
  },
  
  previewMode: 'tree',
  
  isLoading: false,
  error: null,
  
  // 编辑器操作
  setContent: (content: string) => {
    set({ 
      content, 
      lastModified: new Date(),
      isDirty: true 
    });
    
    // 自动验证
    get().validateContent();
    
    // 自动保存到本地存储
    if (get().settings.autoSave) {
      saveContent(content);
    }
  },
  
  setCursorPosition: (position: number) => {
    set({ cursorPosition: position });
  },
  
  setFilename: (filename: string) => {
    set({ filename, lastModified: new Date() });
  },
  
  markDirty: () => {
    set({ isDirty: true, lastModified: new Date() });
  },
  
  markClean: () => {
    set({ isDirty: false });
  },
  
  // 设置操作
  updateSettings: (newSettings: Partial<UserSettings>) => {
    const settings = { ...get().settings, ...newSettings };
    set({ settings });
    saveSettings(settings);
  },
  
  resetSettings: () => {
    set({ settings: DEFAULT_SETTINGS });
    saveSettings(DEFAULT_SETTINGS);
  },
  
  // 验证操作
  validateContent: () => {
    const { content } = get();
    const validation = validateYAML(content);
    set({ validation });
  },
  
  // 预览操作
  setPreviewMode: (mode: PreviewMode) => {
    set({ previewMode: mode });
  },
  
  // 应用状态操作
  setLoading: (loading: boolean) => {
    set({ isLoading: loading });
  },
  
  setError: (error: string | null) => {
    set({ error });
  },
  
  // 文件操作
  newFile: () => {
    set({
      content: EXAMPLE_YAML,
      filename: 'untitled.yaml',
      isDirty: false,
      lastModified: new Date(),
      cursorPosition: 0,
      error: null
    });
    
    get().validateContent();
    saveContent(EXAMPLE_YAML);
  },
  
  loadFile: (content: string, filename = 'imported.yaml') => {
    set({
      content,
      filename,
      isDirty: false,
      lastModified: new Date(),
      cursorPosition: 0,
      error: null
    });
    
    get().validateContent();
    saveContent(content);
  },
  
  saveFile: () => {
    const { content } = get();
    saveContent(content);
    set({ isDirty: false });
  },
  
  // 初始化
  initialize: () => {
    try {
      // 加载用户设置
      const settings = loadSettings();
      
      // 加载编辑器内容
      const savedContent = loadContent();
      const content = savedContent || EXAMPLE_YAML;
      
      set({
        settings,
        content,
        isDirty: false,
        lastModified: new Date(),
        error: null
      });
      
      // 验证内容
      get().validateContent();
    } catch (error) {
      console.error('初始化失败:', error);
      set({ 
        error: '初始化失败，使用默认设置',
        content: EXAMPLE_YAML,
        settings: DEFAULT_SETTINGS
      });
    }
  }
}));

// 自动保存定时器
let autoSaveTimer: NodeJS.Timeout | null = null;

// 监听设置变化，更新自动保存
let previousAutoSave = false;
let previousInterval = 30;

useEditorStore.subscribe((state) => {
  const { autoSave, autoSaveInterval } = state.settings;
  
  if (autoSave !== previousAutoSave || autoSaveInterval !== previousInterval) {
    if (autoSaveTimer) {
      clearInterval(autoSaveTimer);
      autoSaveTimer = null;
    }
    
    if (autoSave) {
      autoSaveTimer = setInterval(() => {
        const { content, isDirty } = useEditorStore.getState();
        if (isDirty) {
          saveContent(content);
          useEditorStore.getState().markClean();
        }
      }, autoSaveInterval * 1000);
    }
    
    previousAutoSave = autoSave;
    previousInterval = autoSaveInterval;
  }
});